package com.zjq.smartdevice.events.listeners;

import com.zjq.smartdevice.events.DevicePowerEvent;
import com.zjq.smartdevice.pojo.SysDevice;
import com.zjq.smartdevice.service.SysDeviceService;
import com.zjq.smartdevice.utils.RequestUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.event.EventListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * @User zhangjiaqi
 * @Project project
 * @Package com.zjq.smartdevice.events.listeners
 * @Date 2022/3/24 17:31
 */
@Component
public class DevicePowerListener {

    private SysDeviceService service;

    @Autowired
    public void setService(SysDeviceService service) {
        this.service = service;
    }

    @EventListener
    @Async
    public void onEvent(DevicePowerEvent event) {
        String deviceId = event.getDeviceId();
        String ip = event.getIp();
        String location = RequestUtil.getLocationByIp(ip);//获取到地区
        SysDevice sysDevice = new SysDevice();
        sysDevice.setDeviceId(deviceId);

        switch (event.getDeviceStatus()) {
            case ONLINE:
                sysDevice.setConnectTime(new Date());
                sysDevice.setCurrentConnectIp(ip);
                sysDevice.setConnectLocation(location);
                sysDevice.setIsOnline(1L);//设置在线
            case OFFLINE:
                sysDevice.setLostConnectTime(new Date());
                sysDevice.setIsOnline(2L);//设置离线
                break;
        }
        service.updateDeviceById(sysDevice);

    }
}
